import 'package:flutter_admin/api/odoo/mps_order_line_odoo_api.dart';
import 'package:flutter_admin/models/odoo/mps_order_line.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

import 'mps_order_line_dialog.dart';

class MpsOrderLineList extends StatefulWidget {
  final String? comment;

  MpsOrderLineList({Key? key, required this.comment}) : super(key: key);
  @override
  _MpsOrderLineListState createState() => _MpsOrderLineListState();
}

class _MpsOrderLineListState extends State<MpsOrderLineList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  MpsOrderLine mpsOrderLine = MpsOrderLine();
  List<MpsOrderLine> selectedList = [];
  DateFormat format = DateFormat('yyyy-MM-dd');
  List<SelectOptionVO> availableList = [];
  List<SelectOptionVO> stateList = [];
  @override
  void initState() {
    super.initState();
    mpsOrderLine.state = widget.comment;
    if (widget.comment == 'purchase') {
      mpsOrderLine.available = 'true';
    }
    mpsOrderLine.dateDemandStart = Utils.getDate();
    mpsOrderLine.dateDemandEnd = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    availableList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: 'true', label: "是"),
      SelectOptionVO(value: 'false', label: "否"),
    ];
    if (widget.comment == 'draft') {
      stateList = [
        SelectOptionVO(value: '', label: ""),
        SelectOptionVO(value: 'draft', label: "新需求"),
        SelectOptionVO(value: 'purchase', label: "采购中"),
      ];
    }
    _query();
  }

  stateMap(e) {
    return e == 'draft'
        ? '新需求'
        : e == 'purchase'
            ? '采购中'
            : e == 'cancel'
                ? '取消'
                : '--';
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '交货开始时间',
            value: mpsOrderLine.dateDemandStart,
            lastDate: isNotBlank(mpsOrderLine.dateDemandEnd)
                ? format.parse(mpsOrderLine.dateDemandEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              mpsOrderLine.dateDemandStart = v;
              setState(() {});
            },
            onSaved: (v) {
              mpsOrderLine.dateDemandStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '交货结束时间',
            value: mpsOrderLine.dateDemandEnd,
            firstDate: isNotBlank(mpsOrderLine.dateDemandStart)
                ? format.parse(mpsOrderLine.dateDemandStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              mpsOrderLine.dateDemandEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              mpsOrderLine.dateDemandEnd = v;
            },
          ),
          CryInput(
            width: 160,
            label: '订单号',
            value: mpsOrderLine.origin,
            onSaved: (v) {
              mpsOrderLine.origin = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品名称',
            value: mpsOrderLine.productName,
            onSaved: (v) {
              mpsOrderLine.productName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品编码',
            value: mpsOrderLine.defaultCode,
            onSaved: (v) {
              mpsOrderLine.defaultCode = v;
            },
          ),
          (widget.comment == 'draft' || widget.comment == 'cancel')
              ? CrySelect(
                  width: 200,
                  label: '是否齐套',
                  dataList: availableList,
                  value: mpsOrderLine.available,
                  onSaved: (v) {
                    mpsOrderLine.available = v;
                  },
                )
              : Text(''),
          widget.comment == 'draft'
              ? CrySelect(
                  width: 200,
                  label: '状态',
                  dataList: stateList,
                  value: mpsOrderLine.state,
                  onSaved: (v) {
                    mpsOrderLine.state = v;
                  },
                )
              : Text(''),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('订单号')),
        DataColumn(label: Text('客户名称')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('优先级')),
        DataColumn(label: Text('交货日期')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('是否齐套')),
        DataColumn(label: Text('状态')),
      ],
      getCells: (m) {
        MpsOrderLine mpsOrderLine = MpsOrderLine.fromMap(m);
        return [
          DataCell(Text(mpsOrderLine.origin ?? '--')),
          DataCell(Text(mpsOrderLine.partnerName ?? '--')),
          DataCell(Text(mpsOrderLine.productName ?? '--')),
          DataCell(Text(mpsOrderLine.defaultCode ?? '--')),
          DataCell(Text(mpsOrderLine.description ?? '--')),
          DataCell(Text(mpsOrderLine.uom ?? '--')),
          mpsOrderLine.state == 'draft'
              ? DataCell(
                  CryInputNum(
                    width: 100,
                    padding: 0,
                    contentPadding: 0,
                    value: mpsOrderLine.priority,
                    onChange: (v) {
                      m["newPriority"] = v;
                    },
                  ),
                  showEditIcon: true, onTap: () {
                  _updatePriority();
                })
              : DataCell(Text(mpsOrderLine.priority != null
                  ? mpsOrderLine.priority.toString()
                  : '--')),
          // DataCell(Text(Utils.timeUTC(mpsOrderLine.dateDemand) ?? '--')),
          DataCell(Text(mpsOrderLine.dateDemand ?? '--')),
          DataCell(Text(mpsOrderLine.qtyOrder ?? '--')),
          DataCell(Text(mpsOrderLine.available == 'true' ? '是' : '否')),
          DataCell(Text(stateMap(mpsOrderLine.state))),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        widget.comment == 'draft'
            ? CryButton(
                label: "获取需求",
                iconData: Icons.view_headline,
                onPressed:
                    selectedList.length != 0 && _checkDrafts(selectedList)
                        ? () => _toPurchase(selectedList)
                        : null,
              )
            : Text(''),
        (widget.comment == 'draft' || widget.comment == 'purchase')
            ? CryButton(
                label: "取消需求",
                iconData: Icons.view_headline,
                onPressed: selectedList.length != 0
                    ? () => _toCancel(selectedList)
                    : null,
              )
            : Text(''),
        widget.comment == 'cancel'
            ? CryButton(
                label: "改为新需求",
                iconData: Icons.view_headline,
                onPressed: selectedList.length != 0
                    ? () => _toDraft(selectedList)
                    : null,
              )
            : Text(''),
        widget.comment == 'purchase'
            ? CryButton(
                label: "订单排产",
                iconData: Icons.view_headline,
                onPressed: selectedList.length != 0
                    ? () => _toActionProduce(selectedList)
                    : null,
              )
            : Text(''),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  bool _checkDrafts(List<MpsOrderLine> selectedList) {
    for (var i = 0; i < selectedList.length; i++) {
      if (selectedList[i].state != 'draft') return false;
    }
    return true;
  }

  _updatePriority() async {
    bool flag = true;
    for (var i = 0; i < page.records.length; i++) {
      var element = page.records[i];
      if (element["newPriority"] != null &&
          element["priority"].toString() != element["newPriority"] &&
          num.parse(element["newPriority"]) <= 100) {
        element["priority"] = num.parse(element["newPriority"]);
        MpsOrderLine mpsOrderLine = MpsOrderLine.fromMap(element);
        await MpsOrderLineApi.saveOrUpdate(mpsOrderLine.toPriorityMap())
            .then((ResponseBodyApi res) {
          if (!res.success!) {
            // CryUtils.message(res.message!);
            flag = false;
            // return;
          }
        });
      }
    }
    if (flag) {
      CryUtils.message("修改成功");
      tableKey.currentState!.loadData(page);
    }
  }

  _toPurchase(List<MpsOrderLine> selectedList) async {
    cryConfirm(context, '确认获取需求？', (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      ResponseBodyApi responseBodyApi =
          await MpsOrderLineApi.changePurchase(['id', 'in', ids]);
      if (responseBodyApi.success!) {
        CryUtils.message('操作成功');
        _query();
      }
    });
  }

  _toCancel(List<MpsOrderLine> selectedList) async {
    cryConfirm(context, '确认取消需求？', (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      ResponseBodyApi responseBodyApi =
          await MpsOrderLineApi.changeCancel(['id', 'in', ids]);
      if (responseBodyApi.success!) {
        CryUtils.message('操作成功');
        _query();
      }
    });
  }

  _toDraft(List<MpsOrderLine> selectedList) async {
    cryConfirm(context, '改为新需求？', (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      ResponseBodyApi responseBodyApi =
          await MpsOrderLineApi.changeDraft(['id', 'in', ids]);
      if (responseBodyApi.success!) {
        CryUtils.message('操作成功');
        _query();
      }
    });
  }

  _toActionProduce(List<MpsOrderLine> selectedList) async {
    cryConfirm(context, '订单排产？', (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      ResponseBodyApi responseBodyApi =
          await MpsOrderLineApi.toActionProduce(['id', 'in', ids]);
      if (responseBodyApi.success!) {
        CryUtils.message('操作成功');
        _query();
      }
    });
  }

  _reset() {
    mpsOrderLine = MpsOrderLine();
    formKey.currentState!.reset();
    mpsOrderLine.state = widget.comment;
    if (widget.comment == 'purchase') {
      mpsOrderLine.available = 'true';
    }
    mpsOrderLine.dateDemandStart = Utils.getDate();
    mpsOrderLine.dateDemandEnd = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await MpsOrderLineApi.page(
        data: {"page": page, "domainList": mpsOrderLine.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<MpsOrderLine> resultList = [];
    ResponseBodyApi responseBodyApi = await MpsOrderLineApi.findAll(data: {
      "domainList": mpsOrderLine.toDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<MpsOrderLine>((e) => MpsOrderLine.fromMap(e))
              .toList() ??
          [];
    }
    return resultList;
  }

  _generateExcel() async {
    List<MpsOrderLine> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'origin',
        'label': '订单号',
        'columnWidth': 10.0,
      },
      {
        'name': 'partnerName',
        'label': '客户名称',
        'columnWidth': 24.0,
      },
      {
        'name': 'defaultCode',
        'label': '产品编码',
        'columnWidth': 24.0,
      },
      {
        'name': 'productName',
        'label': '产品名称',
        'columnWidth': 24.0,
      },
      {
        'name': 'description',
        'label': '规格型号',
        'columnWidth': 32.0,
      },
      {
        'name': 'uom',
        'label': '单位',
        'columnWidth': 10.0,
      },
      {
        'name': 'priority',
        'label': '优先级',
        'columnWidth': 10.0,
      },
      {
        'name': 'dateDemand',
        'label': '交货日期',
        'columnWidth': 19.0,
      },
      {
        'name': 'qtyOrder',
        'label': '数量',
        'columnWidth': 12.0,
      },
      {
        'name': 'available',
        'label': '是否齐套',
        'columnWidth': 12.0,
      },
      {
        'name': 'state',
        'label': '状态',
        'columnWidth': 12.0,
      },
    ];
    Utils.generateExcel(fileName: "销售订单", configure: map, data: selectedList);
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: MpsOrderLineDialog(comment: widget.comment),
      ),
    ).then((v) {
      if (v != null) {
        mpsOrderLine = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<MpsOrderLine>((e) => MpsOrderLine.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.edit && widget.comment == 'cancel') {
          // 改为新需求
          _toDraft(selectedList);
        } else if (v == OperationType.lendOrReturn &&
            widget.comment == 'draft') {
          // 获取需求
          _toPurchase(selectedList);
        } else if ((v == OperationType.delete &&
                widget.comment == 'purchase') ||
            (v == OperationType.delete && widget.comment == 'purchase')) {
          // 取消需求
          _toCancel(selectedList);
        } else if (v == OperationType.handle && widget.comment == 'purchase') {
          // 排产
          _toActionProduce(selectedList);
        } else if (v == OperationType.dmsFile) {
          _generateExcel();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.lendOrReturn,
          enabled: selectedList.length != 0 &&
              widget.comment == 'draft' &&
              _checkDrafts(selectedList),
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length != 0 &&
                widget.comment == 'draft' &&
                _checkDrafts(selectedList),
            title: Text('获取需求'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: (selectedList.length != 0 && widget.comment == 'purchase') ||
              (selectedList.length != 0 && widget.comment == 'draft'),
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled:
                (selectedList.length != 0 && widget.comment == 'purchase') ||
                    (selectedList.length != 0 && widget.comment == 'draft'),
            title: Text('取消需求'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length != 0 && widget.comment == 'cancel',
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length != 0 && widget.comment == 'cancel',
            title: Text('改为新需求'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.handle,
          enabled: selectedList.length != 0 && widget.comment == 'purchase',
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length != 0 && widget.comment == 'purchase',
            title: Text('订单排产'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          child: ListTile(
            leading: const Icon(Icons.import_export_outlined),
            title: Text('导出'),
          ),
        ),
      ],
    );
  }
}
